package com.web.kdl.service.maDataReport;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.web.kdl.common.result.CommonResult;
import com.web.kdl.common.result.CursorPageResult;
import com.web.kdl.dao.maDataReport.DataReportDao;
import com.web.kdl.daoV2.siteWheel.SiteWheelDao;
import com.web.kdl.entity.maDataReport.DataReport;
import com.web.kdl.pojo.CursorPageQuery;
import com.web.kdl.pojo.Vo.ExportTaskVO;
import com.web.kdl.pojo.form.DataReportForm;
import com.web.kdl.service.createTable.TableDataType;
import com.web.kdl.service.createTable.TableType;
import com.web.kdl.service.excel.ExcelService;
import com.web.kdl.service.site.SiteService;
import com.web.kdl.util.TableNameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DataReportServiceImpl implements DataReportService {
    @Resource
    DataReportDao dataReportDao;
    @Resource
    SiteWheelDao siteWheelDao;
    @Resource
    SiteService siteService;
    @Autowired
    private ExcelService excelService;
    @Autowired
    private com.web.kdl.service.excel.ExportTaskManager taskManager;
    @Override
    public List<DataReport> getAlldataReport() {
        ArrayList<DataReport> AllReport = new ArrayList<>();
        List<String> tableList = siteService.getAllSiteDataName(TableDataType.DAY);
        tableList.forEach(tableName -> {
            List<DataReport> dataReports = dataReportDao.selectAllDataReport(tableName);
            AllReport.addAll(dataReports);
        });
        return AllReport;
    }

    @Override
    public List<Map<String, Object>> getDataReport(DataReportForm dataReportForm) {
        ArrayList<DataReport> AllReport = new ArrayList<>();
        List<String> tableList = siteService.getAllSiteDataName(TableDataType.DAY);
        tableList.forEach(tableName -> {
            List<DataReport> dataReports = dataReportDao.selectAllDataReportByTime(tableName,dataReportForm.getStartTime(),dataReportForm.getEndTime());
            AllReport.addAll(dataReports);
        });
        excelService.exportDataReportExcel(AllReport,dataReportForm);
        List<Map<String, Object>> method = method(AllReport);
        return method;
    }

    private List<Map<String, Object>> method(List<DataReport> dataReports) {
        List<Map<String, Object>> result = new ArrayList<>();

        // 一级分组：sum_site
        Map<String, List<DataReport>> bySumSite = dataReports.stream()
                .collect(Collectors.groupingBy(DataReport::getSumSite));

        for (Map.Entry<String, List<DataReport>> sumEntry : bySumSite.entrySet()) {
            String sumSite = sumEntry.getKey();
            List<DataReport> sumSiteReports = sumEntry.getValue();

            Map<String, Object> sumSiteMap = new HashMap<>();
            sumSiteMap.put("name", sumSite);
            List<Map<String, Object>> subSites = new ArrayList<>();

            // 二级分组：sub_site
            Map<String, List<DataReport>> bySubSite = sumSiteReports.stream()
                    .collect(Collectors.groupingBy(DataReport::getSubSite));

            for (Map.Entry<String, List<DataReport>> subEntry : bySubSite.entrySet()) {
                String subSite = subEntry.getKey();
                List<DataReport> subSiteReports = subEntry.getValue();

                Map<String, Object> subSiteMap = new HashMap<>();
                subSiteMap.put("name", subSite);
                List<Map<String, Object>> dataNames = new ArrayList<>();

                // 三级分组：data_name（替换原先的 device_name）
                Map<String, List<DataReport>> byDataName = subSiteReports.stream()
                        .collect(Collectors.groupingBy(DataReport::getDataName));

                for (Map.Entry<String, List<DataReport>> dataNameEntry : byDataName.entrySet()) {
                    String dataName = dataNameEntry.getKey();
                    List<DataReport> dataList = dataNameEntry.getValue();

                    Map<String, Object> dataNameMap = new HashMap<>();
                    dataNameMap.put("name", dataName);
                    dataNameMap.put("data", dataList); // 最底层原始数据列表

                    dataNames.add(dataNameMap);
                }

                subSiteMap.put("children", dataNames);
                subSites.add(subSiteMap);
            }

            sumSiteMap.put("children", subSites);
            result.add(sumSiteMap);
        }
        return result;
    }


    @Override
    public CommonResult getDataReportByParent() {
        return null;
    }

    @Override
    public CursorPageResult<DataReport> getDataReportPage(DataReportForm dataReportForm) {
        try {
            // 获取动态表名
            String dataTempTableName="";
            String dataMinuteTableName="";
            String controlDataTableName="";
            ArrayList<DataReport> AllRecords = new ArrayList<>();
            if (dataReportForm.getFlyWheelName().equals("总控")){
                controlDataTableName = TableNameUtils.getControlDataTableName(dataReportForm.getSiteName(), dataReportForm.getMatrixName());
                List<DataReport> ControlRecords = dataReportDao.selectPageByTime(
                        controlDataTableName,
                        dataReportForm.getStartTime(),
                        dataReportForm.getEndTime(),
                        dataReportForm.getCursorTime(),
                        dataReportForm.getId(),
                        dataReportForm.getIsNext(),
                        dataReportForm.getPageSize() + 1,
                        dataReportForm.getDeviceName()
                );
                AllRecords.addAll(ControlRecords);
            }else{
             dataTempTableName = TableNameUtils.getDataTableName(
                    dataReportForm.getSiteName(), 
                    dataReportForm.getMatrixName(), 
                    dataReportForm.getFlyWheelName(),
                    TableDataType.TEMP
            );
             dataMinuteTableName = TableNameUtils.getDataTableName(
                    dataReportForm.getSiteName(),
                    dataReportForm.getMatrixName(),
                    dataReportForm.getFlyWheelName(),
                    TableDataType.MINUTE
            );
            // 查询数据（pageSize + 1 用于判断是否有更多数据）
            // 查询 当日 上报的 临时数据 每日12点情况
            List<DataReport> TempRecords = dataReportDao.selectPageByTime(
                    dataTempTableName,
                    dataReportForm.getStartTime(),
                    dataReportForm.getEndTime(),
                    dataReportForm.getCursorTime(),
                    dataReportForm.getId(),
                    dataReportForm.getIsNext(),
                    dataReportForm.getPageSize() + 1,
                    dataReportForm.getDeviceName()
            );
            if (TempRecords!=null)
                AllRecords.addAll(TempRecords);

            // 查询数据（pageSize + 1 用于判断是否有更多数据）
            // 查询 上报的 15分钟间隔数据
            List<DataReport> MinuteRecords = dataReportDao.selectPageByTime(
                    dataMinuteTableName,
                    dataReportForm.getStartTime(),
                    dataReportForm.getEndTime(),
                    dataReportForm.getCursorTime(),
                    dataReportForm.getId(),
                    dataReportForm.getIsNext(),
                    dataReportForm.getPageSize() + 1,
                    dataReportForm.getDeviceName()
            );
            if (MinuteRecords!=null)
                AllRecords.addAll(MinuteRecords);
            }
            // 构建分页结果
            return buildCursorResultByTime(AllRecords, dataReportForm);
        } catch (Exception e) {
            throw new RuntimeException("游标分页查询失败", e);
        }
    }

    @Override
    public CommonResult exportDataExcel(DataReportForm dataReportForm) {
        String dataTempTableName = TableNameUtils.getDataTableName(
                dataReportForm.getSiteName(),
                dataReportForm.getMatrixName(),
                dataReportForm.getFlyWheelName(),
                TableDataType.TEMP
        );
        String dataMinuteTableName = TableNameUtils.getDataTableName(
                dataReportForm.getSiteName(),
                dataReportForm.getMatrixName(),
                dataReportForm.getFlyWheelName(),
                TableDataType.MINUTE
        );
        excelService.exportDataReportExcelAsync(
                UUID.randomUUID().toString(),
                dataTempTableName,
                dataMinuteTableName,
                dataReportForm
        );
        return null;
    }

    @Override
    public CommonResult submitExportTask(DataReportForm dataReportForm) {
        // 生成任务ID
        String taskId = UUID.randomUUID().toString();
        
        // 创建任务
        ExportTaskVO task = taskManager.createTask(taskId);
        
        // 获取表名
        String dataTempTableName = TableNameUtils.getDataTableName(
                dataReportForm.getSiteName(),
                dataReportForm.getMatrixName(),
                dataReportForm.getFlyWheelName(),
                TableDataType.TEMP
        );
        String dataMinuteTableName = TableNameUtils.getDataTableName(
                dataReportForm.getSiteName(),
                dataReportForm.getMatrixName(),
                dataReportForm.getFlyWheelName(),
                TableDataType.MINUTE
        );
        
        // 异步执行导出
        excelService.exportDataReportExcelAsync(taskId, dataTempTableName, dataMinuteTableName, dataReportForm);
        
        return CommonResult.success(task);
    }


    private CursorPageResult<DataReport> buildCursorResultByTime(List<DataReport> records, CursorPageQuery query) {
        boolean hasExtra = records.size() > query.getPageSize();
        List<DataReport> resultRecords = hasExtra ?
                records.subList(0, query.getPageSize()) : records;

        java.time.LocalDateTime nextCursor = null;
        java.time.LocalDateTime prevCursor = null;
        boolean hasNext = false;
        boolean hasPrev = false;
        String nextId=null;
        String pervId=null;

        if (!resultRecords.isEmpty()) {
            if (Boolean.TRUE.equals(query.getIsNext())) {
                // 下一页模式
                hasNext = hasExtra;
                hasPrev = query.getCursorTime() != null;

                if (hasNext) {
                    DataReport lastRecord = resultRecords.get(resultRecords.size() - 1);
                    nextCursor = lastRecord.getTime();
                    nextId= String.valueOf(lastRecord.getId());
                }
                if (hasPrev) {
                    DataReport firstRecord = resultRecords.get(0);
                    prevCursor = firstRecord.getTime();
                    pervId= String.valueOf(firstRecord.getId());
                }
            } else {
                // 上一页模式
                hasPrev = hasExtra;
                hasNext = query.getCursorTime() != null; // ✅ 修复：只有传了游标才有下一页

                // 上一页查询结果是倒序的，需要反转
                Collections.reverse(resultRecords);
                if (hasNext) {
                    DataReport lastRecord = resultRecords.get(resultRecords.size() - 1);
                    nextCursor = lastRecord.getTime();
                    nextId= String.valueOf(lastRecord.getId());
                }
                if (hasPrev) {
                    DataReport firstRecord = resultRecords.get(0);
                    prevCursor = firstRecord.getTime();
                    pervId= String.valueOf(firstRecord.getId());
                }
            }
        }

        return CursorPageResult.<DataReport>builder()
                .records(resultRecords)
                .hasNext(hasNext)
                .hasPrev(hasPrev)
                .nextCursor(nextCursor)
                .prevCursor(prevCursor)
                .nextId(nextId)
                .prevId(pervId)
                .total((long) resultRecords.size())
                .build();
    }
}
